package com.yunshipei.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yunshipei.EnterApplication;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.GroupTabAndContact;
import com.yunshipei.utils.CheckSdCard;

import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;

import io.rong.app.utils.StringUtilSub;

public class SortAdapter extends BaseAdapter implements SectionIndexer {
    private static final int GROUPTAB = 1;
    private static final int TYPEMEMBER = 2;
    private GroupTabAndContact groupTabAndContact = null;
    private Context mContext;
    private BitmapDrawable drawable;
    private ListView mListView;

    private LruCache<String, BitmapDrawable> mMemoryCache;

    public SortAdapter(Context mContext, GroupTabAndContact groupTabAndContact) {
        this.mContext = mContext;
        this.groupTabAndContact = groupTabAndContact;

        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 20;
        mMemoryCache = new LruCache<String, BitmapDrawable>(cacheSize) {

            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                // TODO Auto-generated method stub
                if (value != null && value.getBitmap() != null) {
                    return value.getBitmap().getByteCount();
                } else {
                    return 0;
                }
            }

        };
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param groupTabAndContact
     */
    public void updateListView(GroupTabAndContact groupTabAndContact) {
        this.groupTabAndContact = groupTabAndContact;
        notifyDataSetChanged();
    }

    public int getCount() {
        /**
         * 常用通信录+"群消息"
         */
        if (this.groupTabAndContact == null)
            return 0;
        else
            return this.groupTabAndContact.getmSortList().size() + 1;
    }

    public Object getItem(int position) {
        if (position < 1) {
            return groupTabAndContact.getGroupTab();
        } else {
            return groupTabAndContact.getmSortList().get(position - 1);
        }
    }

    public long getItemId(int position) {
        return position;
    }

    public int getItemViewType(int position) {
        if (position < 1)
            return this.GROUPTAB;
        else
            return this.TYPEMEMBER;
    }

    public int getViewTypeCount() {
        return 3;
    }

    public View getView(int position, View view, ViewGroup parent) {
        if (mListView == null) {
            mListView = (ListView) parent;
        }
        ViewHolder viewHolder = null;
        GroupTabHolder groupTabHolder = null;
        int itemType = getItemViewType(position);
        if (view == null) {
            switch (itemType) {
                case GROUPTAB:
                    /**
                     *do somethings about groupTab
                     */
                    groupTabHolder = new GroupTabHolder();
                    view = LayoutInflater.from(mContext).inflate(R.layout.group_info_tab, null);
                    groupTabHolder.GroupTabName = (TextView) view.findViewById(R.id.group_tab_name);
                    groupTabHolder.avatar = (ImageView) view.findViewById(R.id.group_tab_avatar);
                    view.setTag(groupTabHolder);
                    break;
                case TYPEMEMBER:
                    viewHolder = new ViewHolder();
                    view = LayoutInflater.from(mContext).inflate(R.layout.item_sort_listview, null);
                    viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);    //字母
                    viewHolder.nameTV = (TextView) view.findViewById(R.id.name);        //姓名
                    viewHolder.positionTV = (TextView) view.findViewById(R.id.position);            //职位
                    viewHolder.avatar = (ImageView) view.findViewById(R.id.avatar);            //头像
                    viewHolder.avatarText = (TextView) view.findViewById(R.id.avatarText);
                    view.setTag(viewHolder);
            }

        } else {
            if (view.getTag() instanceof ViewHolder)
                viewHolder = (ViewHolder) view.getTag();
            else
                groupTabHolder = (GroupTabHolder) view.getTag();
        }

        switch (itemType) {
            case GROUPTAB:
                groupTabHolder.GroupTabName.setText(groupTabAndContact.getGroupTab().getName());
                break;
            case TYPEMEMBER:
                viewHolder.avatar.setTag(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getUuid());
                int section = getSectionForPosition(position - 1);

                // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
                if (position - 1 == getPositionForSection(section)) {
                    viewHolder.tvLetter.setVisibility(View.VISIBLE);
                    viewHolder.tvLetter.setText(this.groupTabAndContact.getmSortList().get(position - 1).getSortLetters());
                } else {
                    viewHolder.tvLetter.setVisibility(View.GONE);
                }

                viewHolder.nameTV.setText(substringFixedStr(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getName(), 8));
                //viewHolder.positionTV.setText(substringFixedStr(this.list.get(position).getUserInfo().getPosition(),6));
                viewHolder.positionTV.setText(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getPosition());
                if (judgeChinese(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getName())) {
                    viewHolder.avatarText.setText(getEndword(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getName()));
                } else {
                    viewHolder.avatarText.setText(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getName().substring(0, 1).toString().toUpperCase());
                }
                viewHolder.avatar.setImageResource(MyListViewAdapter.person_logos[(position - 1) % MyListViewAdapter.person_logos.length]);
                String key1 = this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getAvatar();
                /**
                 * add local image
                 */
                if (!TextUtils.isEmpty(key1)) {
                    Bitmap avatarBitmap = CheckSdCard.getInstance().getBitMapFromLocal(key1);
                    if (avatarBitmap != null)
                        drawable = new BitmapDrawable(avatarBitmap);
                    viewHolder.avatarText.setVisibility(View.GONE);
                } else {
                    viewHolder.avatarText.setVisibility(view.VISIBLE);
                }

                if (drawable != null) {
                    //将头像设置到listview上去
                    viewHolder.avatar.setImageDrawable(drawable);
                } else {
                    if (!TextUtils.isEmpty(key1)) {
                        drawable = getBitmapFromMemoryCache(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getAvatar());
                    }
                    if (drawable != null) {
                        //将头像设置到listview上去
                        viewHolder.avatar.setImageDrawable(drawable);
                    } else if (key1 != "") {
                        ((ViewHolder) view.getTag()).avatar.setTag(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getUuid());
//                        BitmapWorkerTask task = new BitmapWorkerTask(viewHolder.avatar, viewHolder.avatarText);
//                        task.execute(this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getAvatar(), this.groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getUuid());
                        String imgUrl = groupTabAndContact.getmSortList().get(position - 1).getUserInfo().getAvatar();
                        Glide.with((Activity) mContext).load(imgUrl).into(viewHolder.avatar);
                    }
                }
                break;
            default:
                break;
        }
        return view;
    }

    /**
     * 将一张图片存储到LruCache中。
     *
     * @param key      LruCache的键，这里传入图片的URL地址。
     * @param drawable LruCache的值，这里传入从网络上下载的BitmapDrawable对象。
     */
    public void addBitmapToMemoryCache(String key, BitmapDrawable drawable) {
        if (!TextUtils.isEmpty(key)) {
            if (getBitmapFromMemoryCache(key) == null) {
                mMemoryCache.put(key, drawable);
            }
        }
    }

    /**
     * 从LruCache中获取一张图片，如果不存在就返回null。
     *
     * @param key LruCache的键，这里传入图片的URL地址。
     * @return 对应传入键的BitmapDrawable对象，或者null。
     */
    public BitmapDrawable getBitmapFromMemoryCache(String key) {
        return mMemoryCache.get(key);
    }

    /**
     * 异步下载图片的任务。
     *
     * @author guolin
     */
    private class BitmapWorkerTask extends AsyncTask<String, Void, BitmapDrawable> {

        private ImageView mImageView;
        private String imageUrl;
        private String uuidString;
        private TextView avatarTextView;

        public BitmapWorkerTask(ImageView imageView, TextView viewText) {
            mImageView = imageView;
            avatarTextView = viewText;
        }

        @Override
        protected BitmapDrawable doInBackground(String... params) {
            imageUrl = params[0];
            uuidString = params[1];
            // 在后台开始下载图片  
            Bitmap bitmap = downloadBitmap(imageUrl);
            SoftReference<Bitmap> sRef = new SoftReference(bitmap);
            bitmap = null;
            BitmapDrawable drawable = new BitmapDrawable(EnterApplication.getApp().getResources(), sRef.get());
            addBitmapToMemoryCache(uuidString, drawable);
            return drawable;
        }

        @Override
        protected void onPostExecute(BitmapDrawable drawable) {
            if (mImageView != null && drawable != null && mImageView.getTag().equals(uuidString)) {
                mImageView.setImageDrawable(drawable);
                Bitmap bitmap = drawable.getBitmap();
                if (bitmap != null) {
                    CheckSdCard.getInstance().addBitmapToLocal(bitmap, uuidString);
                }
            }
        }

        /**
         * 建立HTTP请求，并获取Bitmap对象。
         *
         * @param imageUrl 图片的URL地址
         * @return 解析后的Bitmap对象
         */
        private Bitmap downloadBitmap(String imageUrl) {
            Bitmap bitmap = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
            return bitmap;
        }

    }

    final static class ViewHolder {
        TextView tvLetter, avatarText;//字母
        TextView nameTV, positionTV;
        ImageView avatar;
    }

    final static class GroupTabHolder {
        ImageView avatar;
        TextView GroupTabName;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return groupTabAndContact.getmSortList().get(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount() - 1; i++) {
            String sortStr = groupTabAndContact.getmSortList().get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 提取英文的首字母，非英文字母用#代替。
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        String sortStr = str.trim().substring(0, 1).toUpperCase();
        // 正则表达式，判断首字母是否是英文字母
        if (sortStr.matches("[A-Z]")) {
            return sortStr;
        } else {
            return "#";
        }
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    /**
     * 截取字符串
     *
     * @param originalStr
     * @return
     */
    public static String getEndword(String originalStr) {
        String endWord;
        if (originalStr != null) {
            int len = originalStr.length();
            if (len >= 1) {
                endWord = originalStr.substring(len - 1, len);
            } else {
                endWord = originalStr;
            }
            return endWord;
        } else {
            return "";
        }
    }

    /**
     * 判断是否是汉字
     */
    public boolean judgeChinese(String str) {

        return StringUtilSub.isChinese(str);
    }

    /**
     * @param originalStr 被截取字符串
     * @param subLen      字符串长度标准
     * @return
     */
    private String substringFixedStr(String originalStr, int subLen) {
        String str = null;
        if (originalStr == null) {
            return str = "未知";
        } else if (originalStr.equals("") || originalStr.equals("null")) {
            str = "未知";
        } else {
            int strLen = originalStr.length();
            if (strLen > subLen) {
                str = originalStr.substring(0, subLen);
            } else {
                return originalStr;
            }
        }
        return str;
    }

}
